package redteam.grabthegreen;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gtalkservice.IGTalkService;
import com.google.android.gtalkservice.IGTalkSession;

public class InvitePlayersWindow extends Activity {

	private String[] contactnames=new String[]{"","","","",""};
	private static final String LOG_TAG = "GTalkServiceSample";
    IGTalkSession mGTalkSession = null;
	private int counter;
	private Button mSendButton;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.inviteplayerswindow);

		// when networking works, uncomment this:
		//setUpNetworking();

		counter = 0;

		bindGTalkService();

		ListView playerList = (ListView)findViewById(R.id.playerlist);
		playerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactnames));

		Button addContactButton = (Button)findViewById(R.id.addcontact);
		addContactButton.setText("Add Contact...");
		addContactButton.setOnClickListener(new Button.OnClickListener() {
	    	public void onClick(View v) {
	    		startSubActivity(new Intent(InvitePlayersWindow.this, ContactListWindow.class), 0);
	    	}
	    });

		Button invitePlayersButton = (Button)findViewById(R.id.inviteplayers);
		invitePlayersButton.setText("Invite Players");
		mSendButton = invitePlayersButton;
		mSendButton.setOnClickListener(mOnClickListener);
	}

	public void setUpNetworking() {
		try {
			Socket relay = new Socket("192.168.0.6", 7002);
			Socket gameServer = new Socket("192.168.0.6", 7001);

			final DataInputStream relayData = new DataInputStream(relay.getInputStream());
			final DataOutputStream gameServerData = new DataOutputStream(gameServer.getOutputStream());

			new Thread(new Runnable() {
				public void run() {
					while (true) {
					try {
						int msgType = relayData.readInt();
						int identifier = relayData.readInt();
						String msg = "";
						switch (msgType) {
						case 1:
							msg = msgType + ";" + identifier + ";" + relayData.readInt();

							break;
						case 2:
							msg = msgType + ";" + identifier + ";" + relayData.readUTF();
							break;
						default:
							break;
						}

					}catch (Exception e) {

					}
					}
				}
			});
		}catch(Exception e) {

		}
	}


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }

    private void bindGTalkService() {
        bindService((new Intent()).setComponent(
                com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
                mConnection, 0);
    }

    private boolean isValidUsername(String username) {
        if (TextUtils.isEmpty(username)) {
            return false;
        }

        if (username.indexOf('@') == -1) {
            return false;
        }

        return true;
    }

    private Intent getIntentToSend() {
        Intent intent = new Intent(MessageReceiver.ACTION);
        intent.putExtra("poke", "Hi, I am Sam.");
        intent.putExtra("question", "would you like to eat green eggs and ham?");

        return intent;
    }

    private void showMessage(CharSequence msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the GTalkService has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            IGTalkService GTalkService = IGTalkService.Stub.asInterface(service);

            try {
                mGTalkSession = GTalkService.getDefaultSession();

                if (mGTalkSession == null) {
                    // this should not happen.
                    showMessage(getText(R.string.gtalk_session_not_found));
                    return;
                }
            } catch (DeadObjectException ex) {
                Log.e(LOG_TAG, "caught " + ex);
                showMessage(getText(R.string.found_stale_gtalk_service));
            }

            mSendButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mGTalkSession = null;
            mSendButton.setEnabled(false);
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v == mSendButton) {

            	for (int i = 0; i < contactnames.length; i++) {
	                // use GTalkService to send data message to someone
	                String username = contactnames[0];
	                if (!isValidUsername(username)) {
	                    showMessage(getText(R.string.invalid_username));
	                    return;
	                }

	                if (mGTalkSession == null) {
	                    showMessage(getText(R.string.gtalk_service_not_connected));
	                    return;
	                }

	                try {
	                    mGTalkSession.sendDataMessage(username, getIntentToSend());
	                } catch (DeadObjectException ex) {
	                    Log.e(LOG_TAG, "caught " + ex);
	                    showMessage(getText(R.string.found_stale_gtalk_service));
	                    mGTalkSession = null;
	                    bindGTalkService();
	                }
            	}

            	Intent i = new Intent(InvitePlayersWindow.this, GameRoomWindow.class);
            	startSubActivity(i, 0);
            }
        }
    };

	public void onActivityResult(int requestCode, int resultCode, String data, Bundle extras){

		 // See which child activity is calling us back.
	    switch (resultCode) {
	        case RESULT_OK:
	            // This is the standard resultCode that is sent back if the
	            // activity crashed or didn't doesn't supply an explicit result.
	        	contactnames[counter]= data;
            	counter++;
            	ListView playerList = (ListView)findViewById(R.id.playerlist);
        		playerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactnames));
	            break;

	        default: break;
	    }

	} // end activity Result



} // end class
